package router

import (
	"context"
	"fmt"
	"os"
	"strconv"
	"time"

	"../mode"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

var COLLECTION *mongo.Collection

func init() {
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(
		"mongodb://blogUser:Blog1121!@123.207.198.60:10001/blog",
	))
	if err != nil {
		log.Fatalln("mongo:", err)
	}
	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		log.Fatalln("mongo ping:", err)
	}
	COLLECTION = client.Database("blog").Collection("all")

}

// 修改 sitemap文件

func UpdateAliveArt() {
	fmt.Println("flush sitemap.txt")
	rows, err := D.Query("select id,title,`origin_body`,is_delete from articles")
	if err != nil {
		log.Panicln(err)
	}
	fs, err := os.OpenFile("./static/txt/sitemap.txt", os.O_RDWR, 766)
	if err != nil {
		log.Panicln(err)
	}
	err = fs.Truncate(0)
	if err != nil {
		log.Panicln(err)
	}
	fs.Seek(0, 0)
	art := mode.GetArticlesStruct()
	for rows.Next() {
		rows.Scan(&art.Id, &art.Title, &art.Body, &art.IsDelete)
		if art.IsDelete == 0 {
			fs.Write([]byte("https://www.oreorigin.com/detail/" + strconv.Itoa(art.Id) + "\r\n"))
		}
		UpMongoArticle(*art)
		loadQr(strconv.Itoa(art.Id))
	}
	fs.Close()
	rows.Close()
}
func UpMongoArticle(art mode.Articles) {
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	if rest := COLLECTION.FindOne(ctx, bson.M{"id": art.Id}); rest.Err() == mongo.ErrNoDocuments {
		_, err = COLLECTION.InsertOne(ctx, bson.M{"id": art.Id, "title": art.Title, "body": art.Body, "is_delete": art.IsDelete})
		if err != nil {
			log.Panicln("mongo Insert:", err)
		}
	} else {
		_, err = COLLECTION.ReplaceOne(ctx, bson.M{"id": art.Id}, bson.M{"id": art.Id, "title": art.Title, "body": art.Body, "is_delete": art.IsDelete})
		if err != nil {
			log.Panicln("mongo Replace:", err)
		}
	}
}

type SearchStruct struct {
	Id       int    `json:"id"`
	Title    string `json:"title"`
	IsDelete int    `json:"is_delete"`
}

func MongoSearch(keyword string) []*SearchStruct {
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	cor, err := COLLECTION.Find(ctx, bson.M{"$text": bson.M{"$search": keyword}})
	if err != nil {
		log.Panicln("find err:", err)
	}
	data := make([]*SearchStruct, 0)
	s := new(SearchStruct)
	for cor.Next(ctx) {
		cor.Decode(&s)
		if s.IsDelete == 0 {
			data = append(data, s)
		}
	}
	return data
}

// 需要监听文章的更改
func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

// func ListenArt()  {
// 	conn, err := amqp.Dial("amqp://blog:2232442@123.207.198.60:5672/")
// 	failOnError(err, "Failed to connect to RabbitMQ")
// 	defer conn.Close()
//
// 	ch, err := conn.Channel()
// 	failOnError(err, "Failed to open a channel")
// 	defer ch.Close()
//
// 	err = ch.ExchangeDeclare(
// 		"monitor_blog", // name
// 		"topic",      // type
// 		true,         // durable
// 		false,        // auto-deleted
// 		false,        // internal
// 		false,        // no-wait
// 		nil,          // arguments
// 	)
// 	failOnError(err, "Failed to declare an exchange")
//
// 	body := bodyFrom(os.Args)
// 	err = ch.Publish(
// 		"monitor_blog",          // exchange
// 		severityFrom(os.Args), // routing key
// 		false, // mandatory
// 		false, // immediate
// 		amqp.Publishing{
// 			ContentType: "application/json",
// 			Body:        []byte(body),
// 		})
// 	failOnError(err, "Failed to publish a message")
//
// 	log.Printf(" [x] Sent %s", body)
// }
// func bodyFrom(args []string) string {
// 	var s string
// 	if (len(args) < 3) || os.Args[2] == "" {
// 		s = "hello"
// 	} else {
// 		s = strings.Join(args[2:], " ")
// 	}
// 	return s
// }
//
// func severityFrom(args []string) string {
// 	var s string
// 	if (len(args) < 2) || os.Args[1] == "" {
// 		s = "anonymous.info"
// 	} else {
// 		s = os.Args[1]
// 	}
// 	return s
// }
